package wikigearsconnector.connect.customrequesentity;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;

public class CustomFileRequestEntity implements RequestEntity {

	byte[] array;
	private String contentType;

	public CustomFileRequestEntity(InputStream is, String contentType, int size) {
		array = initArray(is);
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.contentType = contentType;
	}

	public long getContentLength() {
		return array.length;
	}

	public String getContentType() {
		return this.contentType;
	}

	public boolean isRepeatable() {
		return true;
	}

	public void writeRequest(final OutputStream out) throws IOException {
		byte[] tmp = new byte[4096];
		int i = 0;
		ByteArrayInputStream is = new ByteArrayInputStream(array);
		try {
			while ((i = is.read(tmp)) >= 0) {
				out.write(tmp, 0, i);
			}
		} finally {
			is.close();
		}
	}

	private byte[] initArray(InputStream is) {
		StringBuilder sb = new StringBuilder();

		byte[] tmp = new byte[4096];
		int i = 0;

		try {
			while ((i = is.read(tmp)) >= 0) {
				sb.append(new String(tmp, 0, i));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return sb.toString().getBytes();

	}
}
